//
//  ROMe.swift
//  NeusoftSchool
//
//  Created by 李狗蛋 on 2017/6/5.
//  Copyright © 2017年 李狗蛋. All rights reserved.
//

import UIKit

class ROMe: UITableViewController,orderListDelegate,commentListDelegate {
    
    var orderList:NSMutableArray!
    var commentList:NSMutableArray!
    var orderBtn:UIButton!
    var commentBtn:UIButton!
    
    var userNameTextfiled:UITextField!
    var pwdTextfiled:UITextField!
    var telTextfiled:UITextField!
    var addressTextfield:UITextField!
    
    var flag:Bool = true
    var content:String!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        getOrderList()
        getCommentList()
        setView()
    }
    
    func getOrderList(){
        let urlStr = "http://172.24.10.130:8080/foodService/getAllUserOrder.do"
        let paraDict = ["user_id":userId.intValue]
        AFHTTPRequestOperationManager().post(urlStr, parameters: paraDict, success: { (response:AFHTTPRequestOperation?, data:Any?) in
            let array = data as! NSArray
            self.orderList = array.mutableCopy() as! NSMutableArray
            self.tableView.reloadData()
        }) { (response:AFHTTPRequestOperation?, error:Error?) in
            print(response!.debugDescription)
        }
    }
    
    func getCommentList(){
        let urlStr = "http://172.24.10.130:8080/foodService/getAllUserComment.do"
        let paraDict = ["user_id":userId.intValue]
        AFHTTPRequestOperationManager().post(urlStr, parameters: paraDict, success: { (response:AFHTTPRequestOperation?, data:Any?) in
            let array = data as! NSArray
            self.commentList = array.mutableCopy() as! NSMutableArray
            self.tableView.reloadData()
        }) { (response:AFHTTPRequestOperation?, error:Error?) in
            print(response!.debugDescription)
        }
    }
    
    func setView(){
        tableView.backgroundColor = UIColor.lightGray
        tableView.refreshControl = UIRefreshControl()
        tableView.refreshControl?.addTarget(self, action: #selector(refreshData), for: .valueChanged)
        tableView.register(orderListCell.self, forCellReuseIdentifier: "orderListCell")
        tableView.register(commentListCell.self, forCellReuseIdentifier: "commentListCell")
        
        let headView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 270))
        headView.backgroundColor = UIColor.blue
        
        let imageView = UIImageView(frame: CGRect(x: 20, y: 20, width: 100, height: 100))
        imageView.image = UIImage(named: "IMG.png")
        headView.addSubview(imageView)
        
        let userNameLabel = UILabel(frame: CGRect(x: 130, y: 20, width: 60, height: 20))
        userNameLabel.text = "用户名:"
        userNameLabel.font = UIFont.systemFont(ofSize: 15)
        headView.addSubview(userNameLabel)
        
        userNameTextfiled = UITextField(frame: CGRect(x: 200, y: 20, width: 100, height: 20))
        userNameTextfiled.borderStyle = .roundedRect
        userNameTextfiled.font = UIFont.systemFont(ofSize: 16)
        userNameTextfiled.text = ROLoginReturnModel.userName
        headView.addSubview(userNameTextfiled)
        
        let pwdLabel = UILabel(frame: CGRect(x: 130, y: 50, width: 70, height: 20))
        pwdLabel.text = "用户密码:"
        pwdLabel.font = UIFont.systemFont(ofSize: 15)
        headView.addSubview(pwdLabel)
        
        pwdTextfiled = UITextField(frame: CGRect(x: 200, y: 50, width: 100, height: 20))
        pwdTextfiled.borderStyle = .roundedRect
        pwdTextfiled.font = UIFont.systemFont(ofSize: 16)
        if let user = (ACSimpleKeychain.defaultKeychain() as AnyObject).credentials(forIdentifier: "user1", service: "userpassword") {
            self.pwdTextfiled.text = (user as NSDictionary).value(forKey: ACKeychainPassword) as? String
        }
        headView.addSubview(pwdTextfiled)
        
        let telLabel = UILabel(frame: CGRect(x: 130, y: 80, width: 70, height: 20))
        telLabel.text = "联系电话:"
        telLabel.font = UIFont.systemFont(ofSize: 15)
        headView.addSubview(telLabel)
        
        telTextfiled = UITextField(frame: CGRect(x: 200, y: 80, width: 100, height: 20))
        telTextfiled.borderStyle = .roundedRect
        telTextfiled.font = UIFont.systemFont(ofSize: 16)
        telTextfiled.text = ROLoginReturnModel.mobilenum
        headView.addSubview(telTextfiled)
        
        let addressLabel = UILabel(frame: CGRect(x: 130, y: 110, width: 70, height: 20))
        addressLabel.text = "配送地址:"
        addressLabel.font = UIFont.systemFont(ofSize: 15)
        headView.addSubview(addressLabel)
        
        addressTextfield = UITextField(frame: CGRect(x: 200, y: 110, width: 100, height: 20))
        addressTextfield.borderStyle = .roundedRect
        addressTextfield.font = UIFont.systemFont(ofSize: 16)
        addressTextfield.text = ROLoginReturnModel.address
        headView.addSubview(addressTextfield)
        
        let confirmBtn = UIButton(frame: CGRect(x: 200, y: 150, width: 100, height: 30))
        confirmBtn.setTitle("确认", for: .normal)
        confirmBtn.backgroundColor = UIColor.brown
        confirmBtn.titleLabel?.font = UIFont.systemFont(ofSize: 20)
        confirmBtn.titleLabel?.textAlignment = .center
        confirmBtn.addTarget(self, action: #selector(updateUserInformation), for: .touchUpInside)
        headView.addSubview(confirmBtn)
        
        orderBtn = UIButton(frame: CGRect(x: 0, y: headView.bounds.height-40, width: view.bounds.width/2, height: 40))
        orderBtn.backgroundColor = UIColor.blue
        orderBtn.addTarget(self, action: #selector(showOrderList), for: .touchUpInside)
        orderBtn.titleLabel?.font = UIFont.systemFont(ofSize: 20)
        orderBtn.setTitle("完成订单", for: .normal)
        orderBtn.titleLabel?.textAlignment = .center
        headView.addSubview(orderBtn)
        
        commentBtn = UIButton(frame: CGRect(x: view.bounds.width/2, y: headView.bounds.height-40, width: view.bounds.width/2, height: 40))
        commentBtn.backgroundColor = UIColor.gray
        commentBtn.addTarget(self, action: #selector(showCommentList), for: .touchUpInside)
        commentBtn.titleLabel?.font = UIFont.systemFont(ofSize: 20)
        commentBtn.setTitle("已有评论", for: .normal)
        commentBtn.titleLabel?.textAlignment = .center
        headView.addSubview(commentBtn)
        
        tableView.tableHeaderView = headView
        
        let footView = UIView()
        tableView.tableFooterView = footView
    }
    
    func updateUserInformation(){
        let urlStr = "http://172.24.10.130:8080/foodService/updateUserById.do"
        let paraDict:NSDictionary = ["user_id":userId.intValue,"username":userNameTextfiled.text!,"userpass":pwdTextfiled.text!,"mobilenum":telTextfiled.text!,"address":addressTextfield.text!]
        AFHTTPRequestOperationManager().post(urlStr, parameters: paraDict, success: { (response:AFHTTPRequestOperation?, data:Any?) in
            let alert = UIAlertController(title: "系统提示", message: "修改成功", preferredStyle: .alert)
            let confirm = UIAlertAction(title: "确认", style: .cancel, handler: nil)
            alert.addAction(confirm)
            self.present(alert, animated: true, completion: nil)
        }) { (response:AFHTTPRequestOperation?, error:Error?) in
            print(response!.debugDescription)
        }
    }
    
    func refreshData(){
        if flag{
            getOrderList()
            tableView.reloadData()
            tableView.refreshControl?.endRefreshing()
        }else{
            getCommentList()
            tableView.reloadData()
            tableView.refreshControl?.endRefreshing()
        }
    }
    
    func insertComment(indexPath:IndexPath,content:String){
        let urlStr = "http://172.24.10.130:8080/foodService/insertComment.do"
        let dict = orderList[indexPath.row] as! NSDictionary
        let paraDict:NSDictionary = ["order_id":(dict["order_id"] as! Int),"content":content]
        AFHTTPRequestOperationManager().post(urlStr, parameters: paraDict, success: { (response:AFHTTPRequestOperation?, data:Any?) in
        }) { (response:AFHTTPRequestOperation?, error:Error?) in
            //print(response!.debugDescription)
            self.getCommentList()
        }
    }
    
    func updataComment(indexPath:IndexPath){
        let urlStr = "http://172.24.10.130:8080/foodService/updateComment.do"
        let dict = commentList[indexPath.row] as! NSDictionary
        let paraDict:NSDictionary = ["order_id":(dict["order_id"] as! Int),"content":content]
        AFHTTPRequestOperationManager().post(urlStr, parameters: paraDict, success: { (response:AFHTTPRequestOperation?, data:Any?) in
        }) { (response:AFHTTPRequestOperation?, error:Error?) in
            //print(response!.debugDescription)
            self.getCommentList()
        }
    }
    
    func showOrderList(){
        flag = true
        orderBtn.backgroundColor = UIColor.brown
        commentBtn.backgroundColor = UIColor.gray
        self.getOrderList()
        tableView.reloadData()
    }
    
    func showCommentList(){
        flag = false
        orderBtn.backgroundColor = UIColor.gray
        commentBtn.backgroundColor = UIColor.brown
        self.getCommentList()
        tableView.reloadData()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if flag && orderList != nil{
            return orderList.count
        }else if !flag && commentList != nil{
            return commentList.count
        }
        return 0
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let basicCell:UITableViewCell? = nil
        if flag && orderList != nil{
            let cell = tableView.dequeueReusableCell(withIdentifier: "orderListCell", for: indexPath) as! orderListCell
            cell.selectionStyle = .none
            let dict = orderList[indexPath.row] as! NSDictionary
            cell.indexPath = indexPath
            cell.orderDelegate = self
            cell.textLabel?.text = dict["foodname"] as? String
            cell.priceLabel.text = "\(dict["price"] as! Int)*\(dict["num"] as! Int)=\(dict["sum"] as! Int)元"
            cell.shopNameLabel.text = dict["shopname"] as? String
            cell.addressLabel.text =  dict["shopaddress"] as? String
            return cell
        }else if !flag && commentList != nil{
            let cell = tableView.dequeueReusableCell(withIdentifier: "commentListCell", for: indexPath) as! commentListCell
            let dict = commentList[indexPath.row] as! NSDictionary
            cell.selectionStyle = .none
            cell.indexPath = indexPath
            cell.comment_time = dict["comment_time"] as! String
            cell.commentDelegate = self
            cell.textLabel?.text = "\(dict["content"] as! String)(\(dict["comment_time"] as! String))"
            cell.foodNameLabel.text = dict["foodname"] as? String
            cell.priceLabel.text = "单价:\(dict["price"] as! Int)"
            cell.shopNameLabel.text = "[\(dict["shopname"] as! String)]"
            return cell
        }
        return basicCell!
    }
    
    func addComment(indexPath: IndexPath) {
        let alert = UIAlertController(title: "添加评论", message: nil, preferredStyle: .alert)
        alert.addTextField { (textField:UITextField) in
            NotificationCenter.default.addObserver(self, selector: #selector(self.alertTextfielDidChang), name: NSNotification.Name.UITextFieldTextDidChange, object: textField)
        }
        let confirm = UIAlertAction(title: "确认", style: .cancel) { (_) in
            let textfield = alert.textFields?.first
            self.content = textfield?.text
            self.insertComment(indexPath: indexPath, content: self.content)
            NotificationCenter.default.removeObserver(self, name: .UITextFieldTextDidChange, object: nil)
        }
        confirm.isEnabled = false
        alert.addAction(confirm)
        self.present(alert, animated: true, completion: nil)
    }
    
    func deleteComment(indexPath: IndexPath) {
        let urlStr = "http://172.24.10.130:8080/foodService/deleteComment.do"
        let dict = commentList[indexPath.row] as! NSDictionary
        let paraDict = ["order_id":(dict["order_id"] as! Int)]
        AFHTTPRequestOperationManager().post(urlStr, parameters: paraDict, success: { (response:AFHTTPRequestOperation?, data:Any?) in
            let jsonDict = data as! NSDictionary
            let success = jsonDict["success"] as! String
            if success == "1"{
                self.commentList.removeObject(at: indexPath.row)
                self.tableView.reloadData()
            }else{
                
            }
        }) { (response:AFHTTPRequestOperation?, error:Error?) in
            print(response!.debugDescription)
        }
    }
    
    func alterComment(indexPath: IndexPath, block: @escaping (String) -> Void) {
        let alert = UIAlertController(title: "修改评论", message: nil, preferredStyle: .alert)
        alert.addTextField { (textfield:UITextField) in
            let dict = self.commentList[indexPath.row] as! NSDictionary
            textfield.text = dict["content"] as? String
        }
        let confirm = UIAlertAction(title: "确认", style: .default) { (_) in
            let textfield = alert.textFields?.first
            self.content = textfield?.text
            block(self.content)
            self.updataComment(indexPath: indexPath)
        }
        let cancle = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        alert.addAction(confirm)
        alert.addAction(cancle)
        self.present(alert, animated: true, completion: nil)
    }
    
    func alertTextfielDidChang(){
        if let alert = self.presentedViewController{
            let textfield = (alert as! UIAlertController).textFields?.first
            let confirm = (alert as! UIAlertController).actions.first
            confirm?.isEnabled = textfield!.text!.characters.count > 0
        }
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if flag{
            return 80
        }else{
            return 100
        }
    }
    
}
